//
//  UIViewController+YYAdd.m
//  Commom
//
//  Created by 山刘 on 2019/3/19.
//  Copyright © 2019年 山刘. All rights reserved.
//

#import "UIViewController+YYAdd.h"
#import "UIImage+YYAdd.h"
#import <objc/runtime.h>
#import "SEGScreenSupportRotateDelegate.h"

#if __has_include(<SEGPlatform/UIViewController+SEGNaviAdd.h>)
#import <SEGPlatform/UIViewController+SEGNaviAdd.h>
#else
#import "UIViewController+SEGNaviAdd.h"
#endif

#if __has_include(<Commom/EXTConcreteProtocol.h>)
#import <Commom/EXTConcreteProtocol.h>
#else
#import "EXTConcreteProtocol.h"
#endif

#if __has_include(<SEGPlatform/SEGPlatformManager.h>)
#import <SEGPlatform/SEGPlatformManager.h>
#else
#import "SEGPlatformManager.h"
#endif

@implementation UIViewController (YYAdd)

#pragma mark - 重置导航栏状态

+ (void)load {
    //虽然load只执行一次，但是为了保险起见，我们还是给加个dispatch_once吧，良好的编程习惯，从这里开始
    static dispatch_once_t token;
    dispatch_once(&token, ^{

        SEL orginSel = @selector(viewWillAppear:);
        SEL overrideSel = @selector(overrideViewWillAppear:);

        Method originMethod = class_getInstanceMethod([self class], orginSel);
        Method overrideMethod = class_getInstanceMethod([self class], overrideSel);

        //原来的类没有实现指定的方法，那么我们就得先做判断，把方法添加进去，然后进行替换
        if (class_addMethod([self class], orginSel, method_getImplementation(overrideMethod) , method_getTypeEncoding(originMethod))) {
            class_replaceMethod([self class],
                                overrideSel,
                                method_getImplementation(originMethod),
                                method_getTypeEncoding(originMethod));

        }else{
            //交换实现
            method_exchangeImplementations(originMethod, overrideMethod);
        }
    });
}

- (void)overrideViewWillAppear:(BOOL)animation{
    //这里并不会造成死循环，因为这个时候是去调用原来的ViewWillAppear:(BOOL)animation方法了。
    NSLog(@"🌛 🌛 enter %@", self);
    
    // 如果不属于导航控制器管理 标签控制管理器 或导航控制器是相机 或其他系统类的时候 则不处理
    // 只对SEG开头的控制器做处理
    if (![NSStringFromClass(self.class) hasPrefix:@"SEG"] ||
        [self.navigationController isKindOfClass:[NSClassFromString(@"TZImagePickerController") class]] ||
        [self.navigationController isKindOfClass:[UIImagePickerController class]] ||
        [self.navigationController isKindOfClass:[UITabBarController class]] || !self.navigationController
        ) {
        [self overrideViewWillAppear:animation];
        return;
    }
    
    // 重置导航栏状态
    if (self.navDisplayType != SEGNavigationBarDisplayTypeIgnore) {
        [self.navigationController setNavigationBarHidden:self.navDisplayType == SEGNavigationBarDisplayTypeHide animated:animation];
        self.navigationController.navigationBar.barTintColor = UIColor.whiteColor;
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:UIColor.whiteColor] forBarMetrics:UIBarMetricsDefault];
    }
    
    //    // 侧滑手势冲突处理
    //    if (!self.leftTouchView) {
    //        self.leftTouchView = [[UIView alloc] init];
    //        self.leftTouchView.backgroundColor = [UIColor.orangeColor colorWithAlphaComponent:0.3];
    //        self.leftTouchView.userInteractionEnabled = NO;
    //        [self.view addSubview:self.leftTouchView];
    //        [self.leftTouchView mas_makeConstraints:^(MASConstraintMaker *make) {
    //            make.left.top.bottom.mas_equalTo(0);
    //            make.width.mas_equalTo(10);
    //        }];
    //    }
    //    [self.view bringSubviewToFront:self.leftTouchView];
    
    [self overrideViewWillAppear:animation];
}

#pragma mark - 横竖屏设置
//强制横屏
- (void)forceOrientationLandscape {
    id appdelegate = [UIApplication sharedApplication].delegate;
    if ([appdelegate conformsToProtocol:@protocol(SEGScreenSupportRotateDelegate)]) {
        id<SEGScreenSupportRotateDelegate> tempDelegate = appdelegate;
        tempDelegate.isForceLandscape = YES;
        [tempDelegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];
    }
    
    //强制翻转屏幕，Home键在右边。
    [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight) forKey:@"orientation"];
    //刷新
    [UIViewController attemptRotationToDeviceOrientation];
}

//强制竖屏
- (void)forceOrientationPortrait {
    id appdelegate = [UIApplication sharedApplication].delegate;
    if ([appdelegate conformsToProtocol:@protocol(SEGScreenSupportRotateDelegate)]) {
        id<SEGScreenSupportRotateDelegate> tempDelegate = appdelegate;
        tempDelegate.isForceLandscape = NO;
        [tempDelegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];
    }
    
    //设置屏幕的转向为竖屏
    [[UIDevice currentDevice] setValue:@(UIDeviceOrientationPortrait) forKey:@"orientation"];
    //刷新
    [UIViewController attemptRotationToDeviceOrientation];
}

- (void)setNewOrientation:(BOOL)fullscreen {
    if (fullscreen) {
        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    }else{
        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    }
}

#pragma mark - 返回手势
- (void)seg_popGestureOpen {
    // 启用侧滑返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        //这里对添加到右滑视图上的所有手势启用
        for (UIGestureRecognizer *popGesture in self.navigationController.interactivePopGestureRecognizer.view.gestureRecognizers) {
            popGesture.enabled = YES;
        }
        //若开启全屏右滑，不能再使用下面方法，请对数组进行处理
        //VC.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)seg_popGestureClose {
    // 禁用侧滑返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        //这里对添加到右滑视图上的所有手势禁用
        for (UIGestureRecognizer *popGesture in self.navigationController.interactivePopGestureRecognizer.view.gestureRecognizers) {
            popGesture.enabled = NO;
        }
        //若开启全屏右滑，不能再使用下面方法，请对数组进行处理
        //VC.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

#pragma mark - associate property
- (void)setNavDisplayType:(SEGNavigationBarDisplayType)navDisplayType {
    objc_setAssociatedObject(self, @selector(navDisplayType), @(navDisplayType), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (SEGNavigationBarDisplayType)navDisplayType {
    return [objc_getAssociatedObject(self, _cmd) integerValue];
}

-(void)setObjName:(NSString *)objName{
    objc_setAssociatedObject(self, @selector(objName), objName, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSString *)objName{
     return objc_getAssociatedObject(self, _cmd);
}

- (void)setLeftTouchView:(UIView *)leftTouchView {
    objc_setAssociatedObject(self, @selector(leftTouchView), leftTouchView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIView *)leftTouchView {
    return objc_getAssociatedObject(self, _cmd);
}

@end
